package com.fezs.excel.convert;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.util.List;

/**
 * Excel单元格中的url字符串转图片
 *
 * @author zhukai
 * @since 2023/8/31
 */
public class ExcelStringImageConverter implements Converter<String> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return cellData.getStringValue();
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        List<String> urlList = StrUtil.split(value, StrUtil.C_COMMA);
        if (CollUtil.isEmpty(urlList)) {
            return new WriteCellData<>(StrUtil.EMPTY);
        }
        String url = urlList.get(0);
        if (StrUtil.isBlank(url)) {
            return new WriteCellData<>(StrUtil.EMPTY);
        }
        byte[] bytes = HttpUtil.downloadBytes(url);
        return new WriteCellData<>(bytes);
    }

}
